<template>
  <div class="regulations">
    <div class="regulations_nav">
      <p style="margin-right: 20px">在线课堂</p>
    </div>
    <div class="regulations_content">
      <h1>{{ regulationsDetails.title }}</h1>
      <p class="regulations_content_time">
        发布时间：{{ regulationsDetails.createdAt }}
      </p>
      <p class="regulations_content_time">
        更新时间：{{ regulationsDetails.updatedAt }}
      </p>
      <p class="regulations_content_time">
        类型：{{ regulationsDetails.type }}
      </p>
      <div class="regulations_content_paragraph">
        <p v-html="regulationsDetails.content"></p>
      </div>
      <div class="regulations_content_video">
        <div class="video-notice" v-if="regulationsDetails.img">
          <el-alert
            title="视频文件较大，可能需要较长加载时间"
            type="warning"
            :closable="false">
            <template slot="title">
              <div>
                <p>视频文件有可能较大，请注意：</p>
                <ul>
                  <li>首次加载可能需要较长时间</li>
                  <li>建议使用有线网络或WiFi观看</li>
                  <li>可以使用播放速度调节功能</li>
                </ul>
              </div>
            </template>
          </el-alert>
        </div>
        <video-player
          v-if="regulationsDetails.img"
          class="video-player vjs-custom-skin"
          ref="videoPlayer"
          :options="playerOptions"
          @play="onPlayerPlay"
          @pause="onPlayerPause"
          @timeupdate="onPlayerTimeupdate"
          @ready="onPlayerReady"
        ></video-player>
      </div>
    </div>
  </div>
</template>

<script>
import { findClassRoomById } from "@/api/classRoom";

export default {
  name: "regulations",
  props: ["roomData"],
  watch: {
    roomData: function (val) {
      let _this = this;
      _this.$router.push({
        path: "/onlineClass/regulationsList",
        query: {
          routerName: _this.routerName,
          type: val,
        },
      });
    },
  },
  data() {
    return {
      regulationsDetails: {},
      playerOptions: {
        sources: [{
          type: "",
          src: ""
        }],
        autoplay: false,
        controls: true,
        poster: "",
        aspectRatio: "16:9",
        preload: 'none',
        fluid: true,
        playbackRates: [0.5, 1.0, 1.5, 2.0],
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: true,
          volumePanel: { inline: false },
          playbackRateMenuButton: true,
          fullscreenToggle: true,
          loadProgressBar: true
        },
        html5: {
          nativeVideoTracks: true,
          nativeAudioTracks: true,
          nativeTextTracks: true,
          vhs: {
            overrideNative: true,
            maxBufferSize: 30,
            maxMaxBufferLength: 10,
            segmentSize: 1024 * 1024 * 2
          }
        }
      },
      currentTime: 0,
      player: null,
      lastSaveTime: 0,
      saveInterval: 5000,
    };
  },
  created() {},
  mounted() {
    this.findClassRoomById();
  },
  methods: {
    findClassRoomById() {
      findClassRoomById(this.$route.query.classRoomId).then(async (response) => {
        if (response.data.code === 20000) {
          const { content, createdAt, id, title, updatedAt, type, img, url } =
            response.data.results;
          this.regulationsDetails = {
            content,
            createdAt,
            id,
            title,
            updatedAt,
            type,
            img,
            url,
          };

          if (img) {
            this.playerOptions.sources = [{
              src: img,
              type: 'video/mp4'
            }];
            this.playerOptions.poster = url || '';
          }
        }
      });
    },
    onPlayerReady(player) {
      this.player = player;

      const lastTime = localStorage.getItem(`video-progress-${this.$route.query.classRoomId}`);
      if (lastTime) {
        try {
          this.player.currentTime(parseFloat(lastTime));
        } catch (e) {
          console.warn('Failed to restore video progress:', e);
        }
      }

      player.on('error', () => {
        const error = player.error();
        console.error('Video Error:', error);
      });
    },
    onPlayerPlay() {
      console.log('视频开始播放');
    },
    onPlayerPause() {
      if (this.player) {
        localStorage.setItem(
          `video-progress-${this.$route.query.classRoomId}`,
          this.player.currentTime().toString()
        );
      }
    },
    onPlayerTimeupdate(event) {
      if (this.player) {
        const currentTime = this.player.currentTime();
        const now = Date.now();
        
        if (now - this.lastSaveTime >= this.saveInterval) {
          this.lastSaveTime = now;
          this.savePlaybackProgress(currentTime);
        }
      }
    },
    savePlaybackProgress(time) {
      try {
        localStorage.setItem(
          `video-progress-${this.$route.query.classRoomId}`,
          time.toString()
        );
      } catch (e) {
        console.warn('Failed to save progress:', e);
      }
    }
  },
  beforeDestroy() {
    if (this.player) {
      localStorage.setItem(
        `video-progress-${this.$route.query.classRoomId}`,
        this.player.currentTime().toString()
      );
      this.player.dispose();
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.regulations {
  color: #333;
  .regulations_nav {
    height: 40px;
    background: #f1f1f1;
    text-align: right;
    line-height: 40px;
    font-weight: bold;
    font-size: 21px;
    color: #0a7b19;
  }
  .regulations_content {
    margin-top: 40px;
    margin-bottom: 110px;
    h1 {
      width: 100%;
      text-align: center;
    }
    .regulations_content_time {
      margin-top: 25px;
      font-size: 12px;
      width: 100%;
      text-align: center;
    }
    .regulations_content_paragraph {
      margin-top: 30px;
      font-size: 14px;
      line-height: 24px;
      img {
        max-width: 600px;
        margin-bottom: 20px;
      }
    }
    .regulations_content_video {
      width: 700px;
      height: 400px;
      margin: 50px auto 0;
      .video-player {
        width: 100%;
        height: 100%;
        .video-js {
          max-height: 400px;
          &.vjs-playing {
            .vjs-big-play-button {
              display: none;
            }
          }
          @media (max-width: 768px) {
            max-height: 300px;
          }
        }
      }
    }
  }
}

.video-notice {
  margin-bottom: 20px;
  
  ul {
    margin: 10px 0;
    padding-left: 20px;
    
    li {
      line-height: 1.5;
      color: #666;
    }
  }
}
</style>
